<?php

if ((isset($path[2]) and is_numeric($path[2])) or isset($_POST['post'])) {
	$post_id = isset($_POST['post']) ? $_POST['post_id'] : $path[2];
	$post = $db->fetchRow("SELECT * FROM blog_posts WHERE id=? AND site_id=?", array($post_id, $site['id']));
	$post['revision'] = $db->fetchRow("SELECT * FROM blog_posts_revisions WHERE post_id=? ORDER BY id DESC LIMIT 1", $post['id']);
	$post['revision']['tags'] = implode("\n", $db->fetchCol("SELECT name FROM blog_posts_revisions_tags prt LEFT JOIN cms_tags t ON prt.tag_id=t.id WHERE site_id=? AND prt.revision_id=? ORDER BY t.name", array($site['id'], $post['revision']['id'])));
	
	if (isset($_POST['post'])) {
		$post['revision'] = array_merge($post['revision'], $_POST['post']['revision']);
		if (!$post['revision']['path']) $post['revision']['path'] = make_path($post['revision']['title']);
		
		$errors = array();
		if (!$post['revision']['title']) $errors[] = 'TITLE';
		if (sizeof($errors)) {
			$smarty->assign('errors', $errors);
		} else {
			$smarty->assign('success', true);
			$db->delete('blog_posts_revisions_tags', $db->quoteInto('revision_id=?', $post['revision']['id']));
			unset($post['revision']['id']);
			$tags = explode("\n", trim($post['revision']['tags']));
			unset($post['revision']['tags']);
			
			if ($post['revision']['published_display'] == '') $post['revision']['published_display'] = new Zend_Db_Expr('NULL');
			$db->insert('blog_posts_revisions', array_merge($post['revision'], array('timestamp' => new Zend_Db_Expr('NOW()'), 'published' => new Zend_Db_Expr('NULL'), 'user_id' => $_SESSION['login']['user']['id'])));
			$revision_id = $db->lastInsertId();
			
			foreach($tags as $tag) {
				if (!$tag_id = $db->fetchOne("SELECT id FROM cms_tags WHERE site_id=? AND name=?", array($site['id'], $tag))) {
					$db->insert('cms_tags', array('site_id' => $site['id'], 'name' => $tag));
					$tag_id = $db->lastInsertId();
				}
				$db->insert('blog_posts_revisions_tags', array('revision_id' => $revision_id, 'tag_id' => $tag_id));
			}
			$post['revision']['tags'] = implode("\n", $db->fetchCol("SELECT name FROM blog_posts_revisions_tags prt LEFT JOIN cms_tags t ON prt.tag_id=t.id WHERE site_id=? AND prt.revision_id=? ORDER BY t.name", array($site['id'], $revision_id)));
			
		}
		
	}
	if (is_object($post['revision']['published_display'])) $post['revision']['published_display'] = '';
	$smarty->assign('post', $post);
	header('Content-type: text/xml');
	$smarty->display('blog/posts/post.tpl.taconite');
	
}
else {
	
	if ($_SESSION['paging'][$path_string]['order'] == 'id') $_SESSION['paging'][$path_string]['order'] = 'published_coalesce';
	
	$order = $_SESSION['paging'][$path_string]['order'];
	$filter = isset($_SESSION['paging'][$path_string]['filter']) ? '%' . $_SESSION['paging'][$path_string]['filter'] . '%' : '%';
    
	if (isset($_REQUEST['id'])) {
		$_SESSION['blog_category_id'] = $_REQUEST['id'];
		$_SESSION['paging'][$path_string]['page'] = 1;
	}
	
	if (isset($_SESSION['blog_category_id'])) {
		
		$posts = $db->fetchAll("SELECT p.*, r1.title, r1.body, u.display_name as author, COALESCE(r1.published_display, r1.published, r1.timestamp) AS published_coalesce, GROUP_CONCAT(t.name SEPARATOR ' ') AS tags
		                        FROM blog_posts p
		                        JOIN blog_posts_revisions r1 ON r1.post_id = p.id
		                        LEFT JOIN blog_posts_revisions r2 ON r2.post_id = r1.post_id AND r2.id > r1.id
		                        LEFT JOIN cms_users u ON r1.author_id=u.id
		                        LEFT JOIN blog_posts_revisions_tags rt ON r1.id=rt.revision_id
		                        LEFT JOIN cms_tags t ON rt.tag_id=t.id
		                        WHERE p.category_id=? AND p.site_id=?
		                        GROUP BY p.id, r1.id
		                        HAVING COUNT(r2.id) < 1
		                        AND (title LIKE ? OR body LIKE ? OR author LIKE ? OR tags LIKE ?)
		                        ORDER BY {$order}", array($_SESSION['blog_category_id'], $site['id'], $filter, $filter, $filter, $filter));
		foreach($posts as $i => $post) {
			$posts[$i]['revision'] = $db->fetchRow("SELECT r.*, u.display_name AS author FROM blog_posts_revisions r LEFT JOIN cms_users u ON r.author_id=u.id WHERE post_id=? ORDER BY id DESC LIMIT 1", $post['id']);
			$posts[$i]['revision']['tags'] = join(', ', $db->fetchCol('SELECT t.name FROM blog_posts_revisions_tags prt JOIN cms_tags t ON prt.tag_id=t.id WHERE prt.revision_id=?', $posts[$i]['revision']['id']));
			$posts[$i]['comments'] = $db->fetchOne('SELECT COUNT(*) FROM blog_posts_comments WHERE post_id=?', $post['id']);
		}
		
    
		$page   = $_SESSION['paging'][$path_string]['page'];
		$show   = $_SESSION['paging'][$path_string]['show'];
		$offset = ($page - 1) * $show;
		$total  = count($posts);
    
		$smarty->assign('order', $order);
		$smarty->assign('page', $page);
		$smarty->assign('show', $show);
		$smarty->assign('filter', $filter);
		$smarty->assign('offset', $offset);
		$smarty->assign('total', $total);
    
		$smarty->assign('posts', array_slice($posts, $offset, $show));
    
    
    
	}
	
	if (isset($_REQUEST['id'])) {
		$posts = $db->fetchAll("SELECT
		    p.*, COALESCE(r1.published_display, r1.published, r1.timestamp) AS published_coalesce
		FROM blog_posts p
		JOIN blog_posts_revisions r1 ON r1.post_id = p.id
		LEFT JOIN blog_posts_revisions r2 ON r2.post_id = r1.post_id AND r2.id > r1.id
		WHERE p.category_id=? AND p.site_id=?
		GROUP BY p.id, r1.id
		HAVING COUNT(r2.id) < 1
		ORDER BY published_coalesce DESC", array($_REQUEST['id'], $site['id']));
		foreach($posts as $i => $post) {
			$posts[$i]['revision'] = $db->fetchRow("SELECT r.*, u.display_name AS author FROM blog_posts_revisions r LEFT JOIN cms_users u ON r.author_id=u.id WHERE post_id=? ORDER BY id DESC LIMIT 1", $post['id']);
			$posts[$i]['revision']['tags'] = join(', ', $db->fetchCol('SELECT t.name FROM blog_posts_revisions_tags prt JOIN cms_tags t ON prt.tag_id=t.id WHERE prt.revision_id=?', $posts[$i]['revision']['id']));
			$posts[$i]['comments'] = $db->fetchOne('SELECT COUNT(*) FROM blog_posts_comments WHERE post_id=?', $post['id']);
		}
		$smarty->assign('posts', $posts);
	}
	
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		header('Content-type: text/xml');
		$smarty->display('blog/posts/index.tpl.taconite');
	} else {
		$smarty->display('blog/posts/index.tpl.html');
	}
	
}
